import { Component, OnInit, Input } from '@angular/core';
import { Hero, HEROS } from "../hero";
import { Router } from "@angular/router";
import { HeroService } from "../hero.service";

@Component({
  selector: 'hero-list',
  // templateUrl: './hero-list.component.html',
  // <hero-detail [hero]="selectedHero"></hero-detail>
  template:`
<div *ngIf="selectedHero">
  <h2>
    {{selectedHero.name | uppercase}} is my hero
  </h2>
  <button (click)="gotoDetail()">View Details</button>
  <button class="delete"
  (click)="delete(selectedHero); $event.stopPropagation()">x</button>
</div>

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="selectHero(hero)" [class.selected]="selectedHero === hero">
  <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

  `,
  styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

  constructor(
    private router: Router,
    private heroService: HeroService
  ) { }

  ngOnInit() {
  }
  @Input()heroes:Array<Hero>;
  selectedHero:Hero;
  selectHero(hero:Hero):void{
    this.selectedHero = hero;
  }
  gotoDetail(): void {
    this.router.navigate(['/detail', this.selectedHero.id]);
  }
  delete(hero: Hero): void {
    this.heroService
        .delete(hero.id)
        .subscribe(() => {
          this.heroes = this.heroes.filter(h => h !== hero);
          if (this.selectedHero === hero) { this.selectedHero = null; }
        });
  }
}
